package com.chagee.store.operation.server.config;

import lombok.SneakyThrows;
import org.apache.rocketmq.acl.common.AclClientRPCHook;
import org.apache.rocketmq.acl.common.SessionCredentials;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.remoting.RPCHook;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.converter.MappingJackson2MessageConverter;
import org.springframework.messaging.converter.MessageConverter;

/**
 * @Description
 * @Author chang.jiawei
 * @Date 2024/12/16
 **/
@Configuration
public class RocketMQConfig {
	@Value("${rocketmq-old.name-server}")
	private String oldNameServer;
	@Value("${rocketmq-old.producer.group}")
	private String oldGroup;
	@Value("${rocketmq-old.producer.access-key}")
	private String oldAccessKey;
	@Value("${rocketmq-old.producer.secret-key}")
	private String oldSecretKey;

	@Value("${rocketmq.name-server}")
	private String nameServer;
	@Value("${rocketmq.producer.group}")
	private String group;
	@Value("${rocketmq.producer.access-key}")
	private String accessKey;
	@Value("${rocketmq.producer.secret-key}")
	private String secretKey;

	@Bean
	public MessageConverter messageConverter() {
		// 使用 Jackson 进行 JSON 序列化
		return new MappingJackson2MessageConverter();
	}

	@SneakyThrows
	@Bean(name = "oldProducer")
	public DefaultMQProducer oldProducer() {
		SessionCredentials sc = new SessionCredentials(oldAccessKey, oldSecretKey);
		RPCHook rpcHook = new AclClientRPCHook(sc);
		DefaultMQProducer producer = new DefaultMQProducer(oldGroup, rpcHook);
		producer.setNamesrvAddr(oldNameServer);
		return producer;
	}

	@Bean(name = "oldRocketMQTemplate")
	public RocketMQTemplate oldRocketMQTemplate(MessageConverter converter) {
		RocketMQTemplate rocketMQTemplate = new RocketMQTemplate();
		rocketMQTemplate.setProducer(oldProducer());
		rocketMQTemplate.setMessageConverter(converter);
		return rocketMQTemplate;
	}

	@SneakyThrows
	@Bean(name = "newProducer")
	public DefaultMQProducer newProducer() {
		SessionCredentials sc = new SessionCredentials(accessKey, secretKey);
		RPCHook rpcHook = new AclClientRPCHook(sc);
		DefaultMQProducer producer = new DefaultMQProducer(group, rpcHook);
		producer.setNamesrvAddr(nameServer);
		return producer;
	}

	@Bean(name = "rocketMQTemplate")
	public RocketMQTemplate rocketMQTemplate(MessageConverter converter) {
		RocketMQTemplate rocketMQTemplate = new RocketMQTemplate();
		rocketMQTemplate.setProducer(newProducer());
		rocketMQTemplate.setMessageConverter(converter);
		return rocketMQTemplate;
	}
}
